package com.crdeng.system.security;

import com.crdeng.handler.BusinessException;
import com.crdeng.response.Result;
import com.crdeng.response.ResultCode;
import com.crdeng.system.service.UserService;
import com.crdeng.system.vo.UserRoleVO;
import com.google.gson.Gson;
import io.jsonwebtoken.Jwt;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class JWTValidationFilter extends BasicAuthenticationFilter {

    @Autowired
    private UserService userService;

    public JWTValidationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 过滤请求验证
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String tokens = request.getHeader("token");
        if (StringUtils.isEmpty(tokens)){
           // response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();

            out.print(new Gson().toJson(Result.error().message(ResultCode.USER_NOT_LOGIN.getMessage()).code(ResultCode.USER_NOT_LOGIN.getCode())));
            return;
        }
        UsernamePasswordAuthenticationToken token = setAuthentication(request.getHeader("token"), response);
            if (token==null){
                return;
            }
        SecurityContextHolder.getContext().setAuthentication(token);
        super.doFilterInternal(request, response, chain);
    }

    /**
     * 验证token 并且验证权限
     *
     * @param token
     * @return
     */
    private UsernamePasswordAuthenticationToken setAuthentication(String token,HttpServletResponse response) throws IOException {
        UserRoleVO userRoleVO = JwtUtils.checkJWT(token);
        if (userRoleVO == null) {
            throw  new BusinessException(ResultCode.USER_ACCOUNT_NOT_EXIST.getCode(),ResultCode.USER_ACCOUNT_NOT_EXIST.getMessage());
        }
        boolean flag = JwtUtils.isExpiration(token);
        if (flag){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(new Gson().toJson(Result.error().message(ResultCode.USER_ACCOUNT_EXPIRED.getMessage()).code(ResultCode.USER_ACCOUNT_EXPIRED.getCode())));
            return null;
        }

        List<SimpleGrantedAuthority> userRoleList = JwtUtils.getUserRole(token);
        return new UsernamePasswordAuthenticationToken(userRoleVO, null, userRoleList);
    }
}
